<template>
  <div class="chat">
    <div class="user">
      <div class="search">
        <input v-model="searchInput" class="input" placeholder="搜素好友名称以筛选">
        <div class="add_box">
          <img src="@/assets/img/search.png">
        </div>
      </div>
      <div class="user_list">
        <li :class="item.friendId===currentUserId?'selected':''" v-for="(item) in searchInput?searchLatelyMsg:latelyMsg" @click="switchUser(item)">
          <div class="avatar_box">
            <img v-if="item.avatar===null || item.avatar===''" src="@/assets/img/avatar.jpg">
            <img v-else :src="item.avatar">
            <img v-if="item.online===1" class="online" src="@/assets/img/online.png">
            <img v-else class="online" src="@/assets/img/un_line.png">
          </div>
          <div class="info">
            <div class="name_msg">
              <span class="name">{{item.friendName}}</span>
              <span class="time">{{ item.updateTime }}</span>
            </div>
            <div class="msg">
              {{item.msg}}
            </div>
          </div>
        </li>

      </div>
    </div>
    <div class="chitchat">
      <div v-if="currentUserId" class="top">
        <span>{{ currentUserName }}</span>
      </div>
      <div v-if="currentUserId" class="main">
        <div class="show_chat" @scroll="scroll">
          <!--          好友消息-->
          <div :id="index" :class="msg.fromId!==user.id?'friend':'my'" :key="index" v-for="(msg,index) in msgList">
            <div class="avatar_box">
              <img v-if="msg.avatar===null || msg.avatar===''" class="avatar" src="@/assets/img/avatar.jpg">
              <!--              如果头像像为空，则使用默认头像-->
              <img v-else class="avatar" :src="msg.avatar">
            </div>
            <div class="char_user">
              <span v-if="msg.fromId!==user.id" class="user_name">
                {{msg.friendName}}
              </span>
              <div :class="msg.fromId!==user.id?'msg_left':'msg_right'">
              <span class="msg_text">
                {{ msg.msg }}
              </span>
              </div>
            </div>
          </div>
        </div>
        <div class="input_box">
          <div class="tool">
            <el-popover placement="top" :width="300" trigger="hover">
              <template #reference>
                <div class="tool_box">
                  <img src="@/assets/img/meme.png" alt="">
                </div>
              </template>
              <div class="emoji_list">
                <span @click="applyEmoji(item)" class="emoji" style="cursor: pointer;border-radius: 5px;
                padding: 5px;font-size: 20px;" v-for="item in emojiList">
                  {{item}}
                </span>
              </div>
            </el-popover>

          </div>
          <div class="chat_input_box">
            <div class="chat_input">
              <textarea v-model="textMsg" autofocus @keydown="noEnter" @keyup.enter.exact="send"></textarea>
            </div>
            <div class="send">
              <button class="send_btn" @click="send">发送</button>
            </div>
          </div>
        </div>
      </div>
      <div class="logo" v-else>
        <img src="@/assets/img/logo.png">
      </div>
    </div>
  </div>
</template>

<script setup>
import {wsStore} from "@/store/ws.js";
import emojiList from "@/assets/emoji/index.json"
import {nextTick, onMounted, reactive, ref, watch} from "vue";
import {getLatelyMsg, getMsgRecord, sendMsg} from "@/api/msg/index.js";
import {getUser} from "@/api/login/index.js";
import socketSend from "@/util/socket.js";
import {useRoute} from "vue-router";
import play, {notice} from "@/util/playMsgNitific.js";
import {ElNotification} from "element-plus";
import Notific from "@/components/notific.vue";
import {msgStore} from "@/store/msg.js";

let user = reactive({})
let msgList = ref([])
let latelyMsg = ref([])
let searchLatelyMsg = ref([])
let textMsg = ref("")
let searchInput = ref("")
let currentUserId = ref(null)
let currentUserName = ref(null)
let page = reactive({
  current:1,
  pageSize:10
})
let store = msgStore()
let route = useRoute();

//收到消息监听，带开发
store.$subscribe((mutation,state)=>{
    let msgObj = state.msg
    if(msgObj.fromId!==currentUserId.value){
      setTimeout(()=>{
        getUserLatelyMsg()
        // 显示通知，播放音效
        play()
        ElNotification({
          title:msgObj.from,
          icon:Notific,
          customClass:'success',
          duration: 3000,
          message: msgObj.message,
          offset: 100,
        })
      },500)
    }else {
      setTimeout(()=>{
        getUserMsg(currentUserId.value)
        getUserLatelyMsg()
      },500)
    }
})

watch(searchInput,(value, oldValue, onCleanup)=>{
  if (value){
    for (let i = 0; i < latelyMsg.value.length; i++) {
      if (latelyMsg.value[i].friendName.indexOf(value)!==-1){
        searchLatelyMsg.value.push(latelyMsg.value[i])
      }
    }
  }else {
    searchLatelyMsg.value = []
  }

})

/**
 * 添加表情
 * @param item
 */
function applyEmoji(item){
  textMsg.value = textMsg.value+item
}
function switchUser(friend){
  currentUserId.value = friend.friendId;
  currentUserName.value = friend.friendName;
  page.current = 1
  // 获取当前好友的消息记录
  getUserMsg(currentUserId.value)
}
/**
 * 输入框阻止回车事件
 * @param e
 * @returns {boolean}
 */
function noEnter(e){
  if (!e.shiftKey && e.keyCode === 13) {
    e.cancelBubble = true; //ie阻止冒泡行为
    e.stopPropagation();//Firefox阻止冒泡行为
    e.preventDefault(); //取消事件的默认动作*换行
    //以下处理发送消息代码
    return false;
  }
}

watch(msgList,(value)=>{
  if (value.length<=10){
    nextTick(()=>{
      let dom = document.getElementById(msgList.value.length-1+"")
      if (dom){
        dom.scrollIntoView({
          behavior: "smooth",  // 平滑过渡
        });
      }
    })
  }
},{deep:true})


/**
 * 获取好友的所有聊天记录
 */
function getUserMsg(friendId,page){
  let queryParam = {
    "toId":friendId,
    "current":page && page.current?page.current:1,
    "size":page && page.size?page.size:10
  }
  getMsgRecord(queryParam).then(res=>{
    msgList.value = res.data.data.records
  })
}

/**
 * 获取好友的所有聊天记录
 */
function getHistoryUserMsg(friendId,page){
  let queryParam = {
    "toId":friendId,
    "current":page && page.current?page.current:1,
    "size":page && page.size?page.size:10
  }
  getMsgRecord(queryParam).then(res=>{
    if (res.data.data.records.length>0){
      for (const msg of res.data.data.records.reverse()){
        msgList.value.unshift(msg)
      }
    }
  })
}

/**
 * 获取最近的会话列表
 */
function getUserLatelyMsg(){
  getLatelyMsg().then(res=>{
    latelyMsg.value = res.data.data
  })
}

/**
 * 发送消息到指定好友
 */
function send(){
  if (!textMsg.value){
    notice('warning','空内容不允许发送','警告')
    return
  }
  let msgObj = {
    "toId":currentUserId.value,
    "msg":textMsg.value,
    "type":1
  }
  // websocket发送
  socketSend({
    "to":currentUserId.value,
    "type":2,
    "from":user.id,
    "message":textMsg.value,
  })
  // 发送消息，重新获取消息
  sendMsg(msgObj).then(res=>{
    getUserMsg(currentUserId.value)
    getUserLatelyMsg()
  });
  textMsg.value = ''
}

function scroll(e){
  let ele = e.target;
  if (ele.scrollTop===0) {
    page.current = page.current+1
    getHistoryUserMsg(currentUserId.value,page)
  }
}

onMounted(()=>{
  // 获取当前登录的用户
  getUser().then(res=>{
    user = res.data.data
  })
  // 获取用户最近会话
  getUserLatelyMsg()
  // 获取用户信息
  // getUserMsg();
  if (route.query.uid){
    switchUser({friendId:route.query.uid,friendName:route.query.name})
  }
})
</script>

<style lang="less" scoped>

.chat {
  position: relative;
  display: flex;
  min-height: 600px;
  width: 100%;
  border-radius: 8px;
}


.user {
  flex: 6;
  background-color: #f7f7f7;
  width: 25%;
  border-right: 1px solid rgba(214, 214, 214, 0.8);
  display: flex;
  flex-direction: column;

  .search {
    display: flex;
    height: 55px;
    align-items: center;
    justify-content: space-around;

    .input {
      padding-left: 10px;
      height: 25px;
      background-color: #eaeaea;
      border-radius: 5px;
      border: 1px solid #eaeaea;
      outline: none;
      width: 70%;
    }

    .input:focus {
      border: 1px solid #eaeaea;
      background-color: #f8f8f8;
    }

    .add_box {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 25px;
      height: 25px;
      background-color: #eaeaea;
      border-radius: 3px;
      cursor: pointer;

      img {
        width: 80%;
        height: 80%;
      }
    }
  }

  .user_list {
    flex: 1;
    width: 100%;
    background-color: #e9e7e6;
    overflow-y: scroll;
    .avatar_box{
      height: 100%;
      display: flex;
      align-items: center;
      position: relative;
      .online{
        width: 10px;
        height: 10px;
        position: absolute;
        right: 0px;
        bottom: 8px;
      }
    }
    .selected{
      background-color: #c7c6c5;
    }
    li {
      cursor: default;
      display: flex;
      list-style: none;
      align-items: center;
      height: 60px;

      .info {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: flex-start;
      }

      img {
        margin: 0 10px;
        height: 70%;
        border-radius: 6px;
      }

      .name_msg {
        width: 100%;
        text-align: start;
        .name {
          font-size: 15px;
        }

        .time {
          float: right;
          padding-right: 8px;
          font-size: 12px;
          color: #999;
        }
      }

      .time_box {
        display: flex;
      }

      .msg {
        color: #999999;
        font-size: 14px;
        text-align: start;
        width: 70%;
        overflow:hidden;
        width-space:nowrap;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    li:hover {
      background-color: #d7d7d8;
    }
  }
}

.chitchat {
  border-bottom-right-radius: 8px;
  border-top-right-radius: 8px;
  flex: 13;
  display: flex;
  flex-direction: column;
  background-color: #f3f3f3;
  .logo{
    padding-top: 30%;
  }
  .top {
    text-align: start;
    height: 55px;
    padding-left: 20px;
    line-height: 55px;
    border-bottom: 1px solid rgba(236, 236, 236, 1);
  }

  .main {
    line-height: normal;
    flex: 1;
    display: flex;
    flex-direction: column;

    .show_chat {
      overflow-y: scroll;
      padding: 8px 30px;
      border-bottom: 1px solid rgba(236, 236, 236, 1);
      height: 50vh;
      .avatar_box {
        width: 40px;
        height: 50px;

        .avatar {
          margin-top: 5px;
          display: inline-block;
          border-radius: 5px;
          width: 100%;
        }
      }

      li {
        list-style: none;
      }

      .friend {
        .char_user {
          text-align: start;
          width: 85%;
        }

        display: flex;
        margin-bottom: 20px;

        .user_name {
          display: block;
          color: #b2b2b2;
          font-size: 13px;
          margin-left: 20px;
          margin-top: -5px;
        }
      }

      .my {
        .char_user {
          text-align: end;
          width: 85%;
        }

        display: flex;
        flex-direction: row-reverse;
        margin-bottom: 20px;
        text-align: end;

        .user_name {
          display: block;
          color: #b2b2b2;
          font-size: 13px;
          margin-left: 20px;
          margin-top: -5px;
        }

        .char_user {
          text-align: start;
        }
      }
    }

    .input_box {
      display: flex;
      height: 40%;
      flex-direction: column;

      .tool {
        height: 25px;
        text-align: start;
        padding: 10px 30px;
        .tool_box{
          height: 100%;
          width: 25px;
          text-align: center;
          cursor: pointer;
        }
        img {
          height: 100%;
        }
        .tool_box:hover{
          border-radius: 3px;
          background-color: #c7c7c7;
        }
        .emoji_list{
          display: flex;
          justify-content: space-between;
          flex-direction: row;
        }
      }

      .chat_input_box {
        flex: 1;
        padding: 0 30px;

        .chat_input {
          height: 75%;
          width: 100%;

          textarea {
            font-size: 15px;
            font-family: 微软雅黑 黑体;
            width: 100%;
            height: 80%;
            max-height: 100%;
            overflow-y: scroll;
            border: none;
            background-color: #f3f3f3;
            resize: none;
          }

          textarea:focus {
            outline-style: none;
          }
        }

        .send {
          display: flex;
          justify-content: flex-end;

          .send_btn {
            color: #07c160;
            border-radius: 5px;
            background-color: #e9e9e9;
            height: 30px;
            padding: 3px 45px;
            border: none;
            cursor: pointer;
          }

          .send_btn:hover {
            background-color: #d2d2d2;
            border: none;
          }

          .send_btn:focus {
            outline: none;
          }

          .send_btn:active {
            background-color: #c6c6c6;
          }
        }
      }
    }
  }

}

.msg_text {
  font-size: 14px;
}

.msg_left {
  display: inline-block;
  word-break: break-all;
  position: relative;
  //width: 75%;
  min-height: 20px;
  padding: 8px;
  text-align: start;
  margin-left: 15px;
  border-radius: 10px;
  background: #ebebeb;
  clear: both
}

.msg_left:before {
  position: absolute;
  top: 8px;
  left: -18px;
  padding: 0;
  border: 10px solid;
  border-color: transparent #ebebeb transparent transparent;
  display: block;
  content: '';
  z-index: 9;
}

.msg_right {
  display: inline-block;
  position: relative;
  word-break: break-all;
  //width: 75%;
  min-height: 20px;
  padding: 8px;
  float: right;
  text-align: start;
  margin-right: 15px;
  border-radius: 10px;
  background: #89d961;
  clear: both
}

.msg_right:before {
  position: absolute;
  top: 8px;
  right: -18px;
  padding: 0;
  border: 10px solid;
  border-color: transparent transparent transparent #89d961;
  display: block;
  content: '';
  z-index: 9;
}
</style>